//
//  MainController.swift
//  新浪微博
//
//  Created by mac on 15/10/7.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class MainController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        
        addChildViewControllers()
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        print(tabBar.subviews.count)
        setUpComposeButton()
        print(tabBar.subviews.count)
    }
    
    /// 添加所有子控件
    private func addChildViewControllers() {
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home_selected")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
        
    }

    /// 添加子控制器
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
        // 设置标题
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nvc = UINavigationController(rootViewController: vc)
        
        addChildViewController(nvc)
    }
    
    /// 设置按钮frame
    private func setUpComposeButton() {
    
        let w = tabBar.bounds.width / CGFloat(viewControllers!.count)
        let h = tabBar.bounds.height
        
        let rect = CGRect(x: 0, y: 0, width: w, height: h)
        
        composeButton.frame = CGRectOffset(rect, 2 * w, 0)
    
    }
    
    /// 懒加载按钮
    lazy private var composeButton: UIButton = {
    
        // 自定义按钮
        let button = UIButton()
    
        // 设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 添加到TabBar
        self.tabBar.addSubview(button)
    
        return button
    
    }()

}
